package com.yksj.healthtalk.ui.chatting;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.ChatAdapter.ViewHolder;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoctorChatInputFragment;
import com.yksj.healthtalk.comm.DoctorChatInputFragment.DoctorInputControlListerner;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.R.color;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.doctor.DoctorMainUI;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.ui.friend.FriendMainUI;
import com.yksj.healthtalk.ui.friend.SystemUserInforActivity;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonSeachFromName;
import com.yksj.healthtalk.ui.server.ServerShopSeachActivity;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 系统医生聊天界面
 * @author zhao
 */
public class DoctorChatActivity extends BaseFragmentActivity  implements DoctorInputControlListerner,OnClickListener{
	
	private static final String TAG = DoctorChatActivity.class.getName();
	
	CustomerInfoEntity mEntity;
	ListView mListView;
	DoctorChatAdapter mAdapter;
	DoctorChatInputFragment mChatInputFragment;
	PullToRefreshListView mPullToRefreshListView;
	JSONObject mJsonObject;//
	String mReciverId = "-1";//接收者id
	String mUserId;//发送者id
	String mRetserial = "";
	private PopupWindow mOptionWindow;
	
	//list view长按事件
	@SuppressWarnings("deprecation")
	final GestureDetector mGestureDetector = new GestureDetector(new ChatGestureListener(){
		public void onLongPress(MotionEvent e) {
			boolean isEditor = mAdapter.isEditor();
			if(isEditor){
				mAdapter.setEditor(false);
			}else{
				mAdapter.setEditor(true);
			}
			mChatInputFragment.onChangeEditorMode(!isEditor);
		};
	});
	
	class MJsonHttpResponseHandler extends JsonHttpResponseHandler{
		final MessageEntity mEntity;
		public MJsonHttpResponseHandler(MessageEntity entity) {
			this.mEntity = entity;
		}
		public void onSuccess(int statusCode, JSONObject response) {//成功
			mEntity.setSendState(MessageEntity.STATE_OK);
			if(!isFinishing()){
				final ViewHolder holder = mEntity.viewHolder.get();
				if(holder != null){
					holder.stateCheckbV.setText(mAdapter.getSendStateStr(MessageEntity.STATE_OK));
					holder.stateCheckbV.setChecked(true);
				}
				if(statusCode == 200 && response != null)onMessageReceive(response);
			}
		};
		public void onFailure(Throwable error, String content) {//失败
			mEntity.setSendState(MessageEntity.STATE_FAIL);
			if(!isFinishing()){
				ViewHolder holder = mEntity.viewHolder.get();
				if(holder != null){
					holder.stateCheckbV.setText(mAdapter.getSendStateStr(MessageEntity.STATE_FAIL));
					holder.stateCheckbV.setChecked(false);
				}
			}
		};
		@Override
		public void onFinish() {
			//更新消息类型
			ChatUserHelper.getInstance().updateChatMessageSendState(mEntity);
		}
	}
	
	final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 1://跳转到人体视图
				if(!isFinishing()){
					onStartBoadyActivity(msg.arg1,(String)msg.obj);
				}
				break;
			case 2://接收消息
				if(!isFinishing()){
					MessageEntity messageEntity = new MessageEntity();
					messageEntity.setSendState(MessageEntity.STATE_OK);
					messageEntity.setSenderId(mReciverId);
					messageEntity.setReceiverId(mUserId);
					messageEntity.setType(MessageEntity.TYPE_TEXT);
					messageEntity.setSendFlag(false);
					messageEntity.setContentJsonArray((JSONArray)msg.obj);
					mAdapter.onDataChange(messageEntity);
					mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
				}
				break;
			case 3:
				mAdapter.onDataChange((MessageEntity)msg.obj);
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.chat_doctor_layout);
		mUserId = SmartControlClient.getControlClient().getUserId();
		mEntity = SmartControlClient.getControlClient().getInfoEntity();
		initView();
		initData();
	}
	
	@Override
	public void onBackPressed() {
//		if(mChatInputFragment.mNumberSoftBord.getVisibility() == View.VISIBLE){
//			mChatInputFragment.mNumberSoftBord.setVisibility(View.GONE);
//			return;
//		}else if(mChatInputFragment.mSeekbarSoftbord.getVisibility() == View.VISIBLE){
//			mChatInputFragment.mSeekbarSoftbord.setVisibility(View.GONE);
//			return;
//		}
		super.onBackPressed();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
		if(data == null)return;
		switch(requestCode){
		case 100:
			try{
				String value = data.getStringExtra("parame");
				if(value == null || value.length() == 0)return;
				mJsonObject.put("smsTEXT","就是这些症状了");
				JSONObject jsonObject = new JSONObject(mJsonObject.toString());
			
				mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
				if(!"".equals(mRetserial)){
					mJsonObject.put("smsTEXT",mRetserial +" "+ value);
				}else{
					mJsonObject.put("smsTEXT",value);
				}
				JSONArray array = new JSONArray();
				array.put(jsonObject);
				array.put(mJsonObject);
				MessageEntity messageEntity = new MessageEntity();
				messageEntity.setSendState(MessageEntity.STATE_PROCESING);
				messageEntity.setSenderId(mUserId);
				messageEntity.setReceiverId(mReciverId);
				messageEntity.setType(MessageEntity.TYPE_TEXT);
				messageEntity.setSendFlag(true);
				messageEntity.setContentJsonArray(array);
				mAdapter.onDataChange(messageEntity);
				
				HttpRestClient.doHttpVirtualDoctor(mJsonObject,new MJsonHttpResponseHandler(messageEntity));
			}catch(Exception e){
				e.printStackTrace();
			}
			break;
		case 200://修改资料
			try {
				mJsonObject.put("Modify_flag","1");
				mJsonObject.put("Modify_Content", data.getStringExtra("json"));
				mJsonObject.put("smsTEXT", mJsonObject.getString("smsserial")+" "+data.getStringExtra("json"));
				sendMessage(mJsonObject,"您看填的对不对?");
			} catch (JSONException e) {
			}
			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:
			mChatInputFragment.hideSoftBord();
			onShowOptionMenu(v);
			break;
		case R.id.option_popmenu1://管理发言
			mOptionWindow.dismiss();
			boolean isEditor = mAdapter.isEditor();
			if(isEditor){
				mAdapter.setEditor(false);
			}else{
				mAdapter.setEditor(true);
			}
			mChatInputFragment.onChangeEditorMode(!isEditor);
			break;
		}
	}
	/**
	 * 菜单
	 * @param view
	 */
	private void onShowOptionMenu(View view){
		if(mOptionWindow != null && mOptionWindow.isShowing()){
			mOptionWindow.dismiss();
			return;
		}
		View view2 = getLayoutInflater().inflate(R.layout.window_menu_chat_layout,null);
		ViewGroup group = (ViewGroup)view2.findViewById(R.id.contain);
		for (int i = 0; i < group.getChildCount(); i++) {
			View view3 = group.getChildAt(i);
			view3.setOnClickListener(this);
			view3.setVisibility(View.GONE);
		}
		mOptionWindow = null;
		view2.findViewById(R.id.option_popmenu1).setVisibility(View.VISIBLE);
		mOptionWindow = new PopupWindow(view2,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
		mOptionWindow.setTouchable(true);
		mOptionWindow.setBackgroundDrawable(new BitmapDrawable());
		mOptionWindow.setOutsideTouchable(true);
		mOptionWindow.showAsDropDown(view);
	}
	
	/**
	 * 跳转到人体
	 * @param sex 性别
	 * @param symptomCode 症状编码
	 */
	private void onStartBoadyActivity(int sex,String symptomCode){
		Intent intent = new Intent(this,HumanBodyActivity.class);
		intent.putExtra("sex", sex);
		intent.putExtra("code", symptomCode);
		startActivityForResult(intent,100);
	}

	/**
	 * 发送数据
	 */
	@Override
	public void onMessageSend(String content) {
		if("".equals(content) && "".equals(mRetserial)) return;
		try {
			if(content.length() == 0){
				String retCode = mJsonObject.getString("retCode");
				if("ZJBB001".equals(retCode) 
						|| "ZJBB0012".equals(retCode) 
						|| "ZJBB021".equals(retCode) 
						|| "ZJBB011".equals(retCode)){
					mJsonObject.put("smsTEXT","我没有其他症状了");
				}else{
					mJsonObject.put("smsTEXT","这个问题我清楚了");
				}
				JSONObject jsonObject = new JSONObject(mJsonObject.toString());
				MessageEntity messageEntity = new MessageEntity();
				messageEntity.setSendState(MessageEntity.STATE_PROCESING);
				messageEntity.setSenderId(mUserId);
				messageEntity.setReceiverId(mReciverId);
				messageEntity.setType(MessageEntity.TYPE_TEXT);
				messageEntity.setSendFlag(true);
				
				mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
				if(!"".equals(mRetserial)){
					mJsonObject.put("smsTEXT",mRetserial +" "+ "777");
				}
				JSONArray array = new JSONArray();
				array.put(jsonObject);
				array.put(mJsonObject);
				messageEntity.setContentJsonArray(array);
				mAdapter.onDataChange(messageEntity);
				
				HttpRestClient.doHttpVirtualDoctor(mJsonObject,new MJsonHttpResponseHandler(messageEntity));
			}else{
				mJsonObject.put("smsTEXT",content);
				JSONObject jsonObject = new JSONObject(mJsonObject.toString());
			
				mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
				if(!"".equals(mRetserial)){
					mJsonObject.put("smsTEXT",mRetserial +" "+ content);
				}
				JSONArray array = new JSONArray();
				array.put(jsonObject);
				array.put(mJsonObject);
				MessageEntity messageEntity = new MessageEntity();
				messageEntity.setSendState(MessageEntity.STATE_PROCESING);
				messageEntity.setSenderId(mUserId);
				messageEntity.setReceiverId(mReciverId);
				messageEntity.setType(MessageEntity.TYPE_TEXT);
				messageEntity.setSendFlag(true);
				messageEntity.setContentJsonArray(array);
				messageEntity.setContent(content);
				mAdapter.onDataChange(messageEntity);
				HttpRestClient.doHttpVirtualDoctor(mJsonObject,new MJsonHttpResponseHandler(messageEntity));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送消息
	 * @param content
	 */
	private  void  sendMessage(JSONObject json,String content){
		try {
		JSONObject jsonObject = new JSONObject(json.toString());
		mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		JSONArray array = new JSONArray();
		array.put(jsonObject);
		array.put(json);
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setSendState(MessageEntity.STATE_PROCESING);
		messageEntity.setSenderId(mUserId);
		messageEntity.setReceiverId(mReciverId);
		messageEntity.setType(MessageEntity.TYPE_TEXT);
		messageEntity.setSendFlag(true);
		messageEntity.setContentJsonArray(array);
		messageEntity.setContent(content);
		mAdapter.onDataChange(messageEntity);
		HttpRestClient.doHttpVirtualDoctor(json,new MJsonHttpResponseHandler(messageEntity));
		} catch (JSONException e) {
		
		}
	}
	
	/**
	 * 请求资料 进入跳转聊天
	 */
	private void onFindEntityToChat(final JSONObject jsonObject){
		HttpRestClient.doHttpFindCustomerInfoByCustId(null, null,jsonObject.optString("layinfofunctionid"), SmartFoxClient.getLoginUserId(), new ObjectHttpResponseHandler(this) {
			
			@Override
			public Object onParseResponse(String content) {
				if (TextUtils.isEmpty(content) && content.equalsIgnoreCase("N")) {
					ToastUtil.showShort(getApplicationContext(),R.string.request_error);
				} else {
					try {
						return DataParseUtil.jsonToCustmerInfo(new JSONObject(content));
					} catch (JSONException e) {
					}
				}
				return null;
			}
			@Override
			public void onSuccess(Object response) {
				super.onSuccess(response);
				if(response!=null){
					CustomerInfoEntity entity=(CustomerInfoEntity) response;
					Intent intent =new Intent(DoctorChatActivity.this,ChatActivity.class);
					intent.putExtra(ChatActivity.KEY_CONTENT, jsonObject.optString("retgretting"));
					intent.putExtra(ChatActivity.KEY_PARAME,entity);
					startActivity(intent);
				}
			}
		});
	}
	
	/**
	 * 消息接收处理
	 * @param jsonObject
	 */
	private void onMessageReceive(JSONObject jsonObject){
		try{
			//直接跳转导医护士
			if(3==jsonObject.optInt("retflag")){
				onFindEntityToChat(jsonObject);
				return ;
			}
			mJsonObject.put("zjbb_jump",jsonObject.getString("zjbb_jump"));
			mJsonObject.put("smsfeature",jsonObject.getString("retfeature"));
			mJsonObject.put("smsClass",jsonObject.getString("retClass"));
			mJsonObject.put("smsCode",jsonObject.getString("retCode"));
			mJsonObject.put("vpage",jsonObject.getString("vpage"));
			mJsonObject.put("smsserial",mRetserial=jsonObject.getString("retserial"));
			mJsonObject.put("redflag",jsonObject.getString("redflag"));
			mJsonObject.put("singlemultiple",jsonObject.getString("singlemultiple"));//1单选,2多选
			mJsonObject.put("Modify_Content",jsonObject.getString("modify_Content"));//1单选,2多选
			mChatInputFragment.mChoiceType = jsonObject.getString("singlemultiple");
			
			int manflag = jsonObject.getInt("manflag");
			int retsex = jsonObject.getInt("retsex");//3男童 4女童
			String redflag = jsonObject.getString("redflag");//2年龄键盘 1可变颜色 0不可变
			//跳转到药品列表
			if(manflag == 4){
				if(mRetserial != null && !"".equals(mRetserial.trim())){
					Intent intent = new Intent(this,ChatMedicinalListActivity.class);
					intent.putExtra("code", mRetserial);
					intent.putExtra("title",mAdapter.mList.get(mAdapter.mList.size()-1).getContent());
					startActivity(intent);
				}else{
					Intent intent = new Intent(this,ServerShopSeachActivity.class);
					intent.putExtra("name",new JSONArray(jsonObject.getString("retlist")).getJSONObject(0).getString("cont"));
					intent.putExtra("type",-2);
					startActivity(intent);
				}
			}else if(manflag == 1 || manflag == 3){//跳转到人体视图
				//retserial 回复内容  [{"cont":"3","type":"1"}]
				Message message = mHandler.obtainMessage();
				message.arg1 = retsex;
//				String retlist = jsonObject.getString("retlist");//症状编码
				String retlist = new JSONArray(jsonObject.getString("retlist")).getJSONObject(0).getString("cont");//症状编码
				message.obj = retlist;//症状编码
				message.what = 1;
				mHandler.sendMessageDelayed(message,2000);
			}else if(1==jsonObject.getInt("customer_info")){//mJsonObject.put("Modify_flag","0");
				Intent intent=new Intent(this, DoctorChatMyinformation.class);
				intent.putExtra("modify_Content", jsonObject.getString("modify_Content"));
				startActivityForResult(intent, 200);
			}else{
				if(!"".equals(jsonObject.getString("retclientstr"))){
					String str = jsonObject.getString("retclientstr");
					JSONArray array = jsonObject.optJSONArray("retclientstr_keywords");
					mJsonObject.put("smsTEXT",str);
					mJsonObject.put("redflag","0");
					JSONObject jsonObject2 = new JSONObject(mJsonObject.toString());
					if(array != null && array.length() >0){
						jsonObject2.put("keyWords",array);
					}
					JSONArray array2 = new JSONArray();
					array2.put(jsonObject2);
					array2.put(jsonObject);
					onNewMesgHandler(array2);
				}
				if(jsonObject.getJSONArray("retclient").length() != 0){
					String str = jsonObject.getJSONArray("retclient").toString();
					mJsonObject.put("smsTEXT",str);
					mJsonObject.put("redflag","0");
					JSONObject jsonObject2 = new JSONObject(mJsonObject.toString());
					JSONArray array = new JSONArray();
					array.put(jsonObject2);
					array.put(jsonObject);
					onNewMesgHandler(array);
				}
				
				if(!"".equals(jsonObject.getString("retlist"))){
					String str = jsonObject.getString("retlist");
					JSONArray jsonArray = new JSONArray(str);
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject2 = jsonArray.getJSONObject(i);
						if(jsonObject2.has("type") && 3==jsonObject2.getInt("type")){
							jsonObject2.put("type", 4);
						}
					}
					jsonObject.put("retlist", str.toString());
					mJsonObject.put("smsTEXT",str);
					JSONObject jsonObject2 = new JSONObject(mJsonObject.toString());
					JSONArray array = new JSONArray();
					array.put(jsonObject2);
					array.put(jsonObject);
					jsonObject2.put("redflag", "1");
					onNewMesgHandler(array);
				}
				
				if(!"".equals(jsonObject.getString("retgretting"))){
					String str = jsonObject.getString("retgretting");
					mJsonObject.put("smsTEXT",str);
					mJsonObject.put("redflag","0");
					JSONObject jsonObject2 = new JSONObject(mJsonObject.toString());
					JSONArray array = new JSONArray();
					array.put(jsonObject2);
					array.put(jsonObject);
					onNewMesgHandler(array);
				}
//				if("2".equals(redflag)){//年龄键盘
//					mChatInputFragment.onShowAgeBord();
//				}else if("1".equals(redflag)){//数字键盘
//					mChatInputFragment.onShowNumberBord();
//				}
			}
		}catch(JSONException e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 响应新消息
	 * @param object
	 */
	private void onNewMesgHandler(JSONArray object){
		object.put(mJsonObject);
		Message message = mHandler.obtainMessage();
		message.obj = object;
		message.what = 2;
		mHandler.sendMessageDelayed(message,1000);
	}
	
	private void initView(){
		initTitle();
		setBackBtn("返回",this);
		setTitle("多美医生");
		setRightMore(this);
		mChatInputFragment = (DoctorChatInputFragment)getSupportFragmentManager().findFragmentById(R.id.input_control);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_listview);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.setAdapter(mAdapter = new DoctorChatAdapter(this));
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				onLoadHistoryMesgs();
			}
		});
		mListView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		});
	}
	
	/**
	 * 
	 * 下拉刷新
	 * 
	 */
	private void onLoadHistoryMesgs(){
		final String id = mAdapter.getFirstMesgId();
		new AsyncTask<Void,Void,List<MessageEntity>>() {
			@Override
			protected List<MessageEntity> doInBackground(Void... params) {
				return ChatUserHelper.getInstance().queryChatMessageByAfterId(mUserId,mReciverId,false,id,"10");
			}
			@Override
			protected void onPostExecute(List<MessageEntity> result) {
				if(!isFinishing()){
					if(result.size() != 0){
						mAdapter.onPullDataChange(result);
					}
					mPullToRefreshListView.onRefreshComplete();
				}
			}
		}.execute();
	}
	
	/**
	 * 初始化
	 */
	private void initData(){
		try{
			mJsonObject = new JSONObject();
			mJsonObject.put("Customerid",mUserId);
			mJsonObject.put("terminalid","");
			mJsonObject.put("smsrail","");
			mJsonObject.put("smsType","CLIENT");
			mJsonObject.put("smsCode","");
			mJsonObject.put("retCode","");
			mJsonObject.put("smsClass","");
			mJsonObject.put("retClass","");
			mJsonObject.put("smsfeature","1");
			mJsonObject.put("smsTEXT","");
			mJsonObject.put("vpage","");
			mJsonObject.put("singlemultiple","0");
			mJsonObject.put("zjbb_jump","");
			mJsonObject.put("Modify_Content","");
			mJsonObject.put("Modify_flag","0");
		}catch(JSONException e){
			e.printStackTrace();
		}
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setSendState(MessageEntity.STATE_OK);
		messageEntity.setSenderId(mReciverId);
		messageEntity.setReceiverId(mUserId);
		messageEntity.setType(MessageEntity.TYPE_TEXT);
		messageEntity.setSendFlag(false);
		messageEntity.setContent(getFirstWord());
		
		Message msg = mHandler.obtainMessage();
		msg.obj = messageEntity;
		msg.what = 3;
		mHandler.sendMessageDelayed(msg,1500l);
	}
	
	private String getFirstWord(){
		int i = new Random().nextInt(5);
		switch(i){
		case 1:
			return "您好，您有什么不舒服的吗？";
		case 2:
			return "您好，身体有什么不适吗？";
		case 3:
			return "你好，哪不舒服？";
		case 4:
			return "见到您很高兴，身体怎样，有什么问题吗？";
		case 5:
			return "欢迎您光临，身体有什么不舒服吗？";
		case 6:
			return "您好！我是多美医生，您有什么不舒服的吗？";
		default:
			return "您好，最近怎样？身体有什么不适症状吗？";
		}
	}
	
	public void onSelectAll() {
		mAdapter.onSelectAll();
	}

	public void onDeletAll() {
		mAdapter.onDeletAll();
	}

	public void onDeletSelect() {
		mAdapter.onDeletSelect();
	}
	
	
	
	class DoctorChatAdapter extends BaseAdapter{
		private final SimpleDateFormat hourSdf = new SimpleDateFormat("HH:mm",Locale.getDefault());
		private final SimpleDateFormat yearSdf = new SimpleDateFormat(
				"yy年-MM月-dd日 HH:mm",Locale.getDefault());
		final int VIEWTYPE_COUNT = 5;
		final List<MessageEntity> mList = new ArrayList<MessageEntity>();
		final LayoutInflater mInflater;
		final Context mContext;
		Drawable leftDrawable;
		//发送状态
		final String SEND_OK;
		final String SEND_FAIL;
		final String SEND_PROCESING;
		ConcurrentHashMap<String,Object> mInfoHashMap;
		private final ImageLoader mImageLoader;
		private boolean isEditor = false;//是否是编辑状态
		//已经选择的消息
		private final LinkedHashMap<MessageEntity, MessageEntity> mChoosedMap = new LinkedHashMap<MessageEntity, MessageEntity>();// 已经选中的消息
		
		public DoctorChatAdapter(Context context){
			mContext = context;
			mInfoHashMap = HTalkApplication.getAppData().cacheInformation;
			mImageLoader = ImageLoader.getInstance();
			mInflater = LayoutInflater.from(context);
			leftDrawable = mContext.getResources().getDrawable(R.drawable.home_icondoctress);
			SEND_OK = getString(R.string.chatting_send_over);
			SEND_PROCESING = getString(R.string.chatting_sending);
			SEND_FAIL = getString(R.string.chatting_send_fail);
		}
		
		public void onPullDataChange(List<MessageEntity> list){
			mList.addAll(0,list);
			notifyDataSetChanged();
		}
		
		public void onDataChange(MessageEntity messageEntity){
			ChatUserHelper.getInstance().insertChatMessage(messageEntity);
			mList.add(messageEntity);
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public MessageEntity getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		public boolean isEditor() {
			return isEditor;
		}
		
		public void onDeletAll() {
			ChatUserHelper.getInstance().deleteChatMessage(mList);
			mList.clear();
			notifyDataSetChanged();
			mChatInputFragment.onUpdateSelectedNumber(0);
		}

		public void onDeletSelect() {
			Collection<MessageEntity> collection = mChoosedMap.values();
			ChatUserHelper.getInstance().deleteChatMessage(collection);
			mList.removeAll(collection);
			notifyDataSetChanged();
			mChatInputFragment.onUpdateSelectedNumber(0);
		}
		
		/**
		 * 全选
		 */
		public void onSelectAll() {
			for (MessageEntity msg : mList) {
				mChoosedMap.put(msg, msg);
			}
			notifyDataSetChanged();
			mChatInputFragment.onUpdateSelectedNumber(mChoosedMap.size());
		}
		
		public String getFirstMesgId(){
			String id = null;
			for (MessageEntity msg : mList) {
				if(msg.getType() != MessageEntity.TYPE_TIME){
					id = msg.getId();
					break;
				}
			}
			if(id == null)id = String.valueOf(Long.MAX_VALUE);
			return id;
		}
		
		/**
		 * 获取聊天内容
		 * @param jsonObject
		 * @return
		 */
		public String getContent(JSONObject jsonObject){
			try {
				return jsonObject.getString("smsTEXT");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
		
		public String getSmsClass(JSONObject jsonObject){
			try {
				return jsonObject.getString("smsClass");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
		
		public String getSmsCode(JSONObject jsonObject){
			try {
				return jsonObject.getString("smsCode");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
		
		private JSONObject getJsonObject(MessageEntity entity){
			try {
				if(entity.getContentJsonArray() != null && entity.getContentJsonArray().length() !=0)
					return  entity.getContentJsonArray().getJSONObject(0);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return  null;
		}
		
		public String getReplyType(MessageEntity messageEntity){
			JSONObject jsonObject = getJsonObject(messageEntity);
			if(jsonObject != null && jsonObject.has("redflag")){
				try {
					String redflag = jsonObject.getString("redflag");
					return redflag;
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}
		
		public String getRetserial(MessageEntity messageEntity){
			JSONObject jsonObject = getJsonObject(messageEntity);
			if(jsonObject != null && jsonObject.has("smsserial")){
				try {
					String redflag = jsonObject.getString("smsserial");
					return redflag;
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}
		
		/**
		 * 获取聊天内容
		 * @param jsonObject
		 * @return
		 */
		public String getRedflag(JSONObject jsonObject){
			try {
				return jsonObject.getString("redflag");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
		
		/**
		 * 
		 * 获得发送状态
		 * @param state
		 * @return
		 */
		public String getSendStateStr(int state){
			if(state == MessageEntity.STATE_FAIL){
				return SEND_FAIL;
			}else if(state == MessageEntity.STATE_OK){
				return SEND_OK;
			}else if(state == MessageEntity.STATE_PROCESING){
				return SEND_PROCESING;
			}
			return null;
		}
		
		@Override
		public int getItemViewType(int position) {
			final MessageEntity entity = getItem(position);
			int type = entity.getType();
			switch(type){
			case MessageEntity.TYPE_TEXT:
				if(!entity.isSendFlag()) type = -4;
				break;
			}
			return type;
		}
		
		@Override
		public int getViewTypeCount() {
			return VIEWTYPE_COUNT;
		}

		public void setEditor(boolean isEditor) {
			if (this.isEditor == isEditor)
				return;
			this.isEditor = isEditor;
			if (isEditor)
				mChoosedMap.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int type = getItemViewType(position);
			final MessageEntity entity = getItem(position);
			ViewHolder viewHodler = null;
			
			if(convertView == null){
				viewHodler = new ViewHolder();
				convertView = onCreateView(type,viewHodler);
				entity.viewHolder = new WeakReference<ViewHolder>(viewHodler);
			}else{
				viewHodler = (ViewHolder)convertView.getTag();
				entity.viewHolder = new WeakReference<ViewHolder>(viewHodler);
			}
			
			if(entity.isSendFlag()){
				if(mEntity != null){
					mImageLoader.displayImage(mEntity.getSex(),mEntity.getNormalHeadIcon(),viewHodler.headerImageV);
				}else{
					mImageLoader.displayImage("-1",viewHodler.headerImageV);
				}
			}else{
				viewHodler.headerImageV.setImageDrawable(leftDrawable);
			}
			
			onBindData(type,position, getItem(position),viewHodler);
			
			long lastTime = 0;
			if(position > 0){
				final MessageEntity entity2 = getItem(--position);
				lastTime = entity2.getDate();
			}
			setChatTime(viewHodler.timeTextV,lastTime,entity.getDate());
			
			//选择删除模式
			if (viewHodler.chooseBox != null) {
				if (isEditor) {// 编辑状态下
					if (viewHodler.chooseBox.getVisibility() != View.VISIBLE)
						viewHodler.chooseBox.setVisibility(View.VISIBLE);
					viewHodler.chooseBox.setChecked(mChoosedMap.containsValue(entity));
					viewHodler.chooseBox
							.setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									if (mChoosedMap.containsValue(entity)) {
										mChoosedMap.remove(entity);
									} else {
										mChoosedMap.put(entity, entity);
									}
									mChatInputFragment.onUpdateSelectedNumber(mChoosedMap.size());
								}
							});
				} else {
					viewHodler.chooseBox.setVisibility(View.GONE);
				}
			}
			return convertView;
		}
		
		/**
		 * 设置聊天时间
		 * @param textView
		 * @param lastTime
		 * @param currentTime
		 */
		private void setChatTime(TextView textView, long lastTime, long nextTime) {
			// 计算间隔时间
			long intervalTime = nextTime - lastTime;
			intervalTime = Math.abs(intervalTime);
			// 间隔两分钟给予显示
			if (intervalTime <= 120000) {
				textView.setVisibility(View.GONE);
			} else {
				try {
					String timeStr = null;
					// 当前时间
					Date nextday = new Date(nextTime);
					// 计算时间间隔
					int temp = TimeUtil.getChatTime(nextTime);
					switch (temp) {
					case 0:
						timeStr = "今天 " + hourSdf.format(nextday);
						break;
					case 1:
						timeStr = "昨天 " + hourSdf.format(nextday);
						break;
					case 2:
						timeStr = "前天" + hourSdf.format(nextday);
						break;
					default:
						timeStr = yearSdf.format(nextday);
						break;
					}
					textView.setVisibility(View.VISIBLE);
					textView.setText(timeStr);
				} catch (Exception e) {
					e.printStackTrace();
					textView.setVisibility(View.GONE);
				}
			}
		}
		
		/**
		 * 绑定数据
		 * @param type
		 * @param entity
		 * @param viewHolder
		 */
		private void onBindData(int type,final int position,MessageEntity entity,ViewHolder viewHolder){
			CharSequence content = entity.getContent();
			JSONObject object = getJsonObject(entity);
			if(entity.getContentJsonArray()!=null &&entity.getContentJsonArray().length()==3 && content == null && object!=null&& !object.has("keyWords")){
				try {
					JSONArray jsonArray = new JSONArray(entity.getContentJsonArray().getJSONObject(0).getString("smsTEXT"));
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						if(jsonObject.has("type") && jsonObject.optInt("type") ==3){
							jsonObject.put("type", 4);
						}
					}
					viewHolder.contentTextV.setMovementMethod(LinkMovementMethod.getInstance());
					if(entity.contCharSequence == null){
						CharSequence content1 = onParseLinkTxt(entity,jsonArray,viewHolder);
						entity.contCharSequence = content1;
					}
					viewHolder.contentTextV.setText(entity.contCharSequence);
				} catch (Exception e) {
					try {
						viewHolder.contentTextV.setText(entity.getContentJsonArray().getJSONObject(0).getString("smsTEXT"));
					} catch (JSONException e1) {
					}
				}
				
			}else if(content == null){
				//超链接
				if(object.has("keyWords") && object.optJSONArray("keyWords").length()>0){
					viewHolder.contentTextV.setMovementMethod(LinkMovementMethod.getInstance());
					if(entity.contCharSequence == null){
						CharSequence content1 = onParseLinkTxt(entity, object.optJSONArray("keyWords"),viewHolder);
						entity.contCharSequence = content1;
					}
					viewHolder.contentTextV.setText(entity.contCharSequence);
				}else{
					String content1 = getContent(object);
					entity.setContent(content1);
					viewHolder.contentTextV.setText(content1);
				}
			}else{
				viewHolder.contentTextV.setText(content);
			}
//				viewHolder.contentTextV.setMovementMethod(LinkMovementMethod.getInstance());
//				if(entity.contCharSequence == null){
//					CharSequence content1 = onParseLinkTxt(object.optJSONArray("keyWords"),viewHolder);
//					entity.contCharSequence = content1;
//				}
//				viewHolder.contentTextV.setText(entity.contCharSequence);
			final String repType = getReplyType(entity);
			if(type > 0 && viewHolder.stateCheckbV != null){
				viewHolder.stateCheckbV.setText(getSendStateStr(entity.getSendState()));
				viewHolder.stateCheckbV.setChecked(entity.getSendState() == MessageEntity.STATE_OK);
			}
			if(repType != null && "1".equals(repType)){
				viewHolder.contentTextV.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						final MessageEntity messageEntity = mAdapter.getItem(position);
						String type = mAdapter.getReplyType(messageEntity);
						final JSONObject jsonObject = getJsonObject(messageEntity);
						String smsClass = mAdapter.getSmsClass(jsonObject);
						String smsCode = mAdapter.getSmsCode(jsonObject);
						try {
							mJsonObject.put("smsCode",smsCode);
							mJsonObject.put("smsClass",smsClass);
						} catch (JSONException e) {
							e.printStackTrace();
						}
						mRetserial = mAdapter.getRetserial(messageEntity);
						mChatInputFragment.mChoiceType = jsonObject.optString("singlemultiple","1");
						mChatInputFragment.onSoftBordChange(type);
						v.setSelected(true);
						new Handler(){
							public void handleMessage(Message msg) {
								if(messageEntity.viewHolder != null && messageEntity.viewHolder.get().contentTextV != null){
									messageEntity.viewHolder.get().contentTextV.setSelected(true);
								}
							};
						}.sendEmptyMessageDelayed(1,800);
					}
				});
			}
		}
		
		/**
		 * 创建item
		 * @param type
		 * @param viewHolder
		 * @return
		 */
		private View onCreateView(int type,ViewHolder viewHolder){
			switch(type){
			case 4:
				View view = mInflater.inflate(R.layout.chat_right_txt_blue_item_duomei,null);
				view.setTag(viewHolder);
				viewHolder.headerImageV = (ImageView)view.findViewById(R.id.chat_head);
				viewHolder.contentTextV = (TextView)view.findViewById(R.id.chat_content);
				viewHolder.stateCheckbV = (CheckBox)view.findViewById(R.id.msg_state);
				viewHolder.timeTextV = (TextView) view.findViewById(R.id.chat_time);
				viewHolder.chooseBox = (CheckBox)view.findViewById(R.id.selected);
				viewHolder.headerImageV.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(DoctorChatActivity.this,PersonalInformationActivity.class);
						startActivity(intent);
					}
				});
				
				if(viewHolder.contentTextV!=null){
					viewHolder.contentTextV.setLineSpacing(5f, 1.1f);
				}
				return view;
			case -4:
				view = mInflater.inflate(R.layout.chat_left_txt_white_item,null);
				view.setTag(viewHolder);
				viewHolder.headerImageV = (ImageView)view.findViewById(R.id.chat_head);
				viewHolder.contentTextV = (TextView)view.findViewById(R.id.chat_content);
				viewHolder.timeTextV = (TextView) view.findViewById(R.id.chat_time);
				viewHolder.chooseBox = (CheckBox)view.findViewById(R.id.selected);
				viewHolder.headerImageV.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						//系统医生
						Intent intent = new Intent(DoctorChatActivity.this,SystemUserInforActivity.class);
						intent.putExtra("id","-1");
						startActivity(intent);
					}
				});
				
				if(viewHolder.contentTextV!=null){
					viewHolder.contentTextV.setLineSpacing(5f, 1.1f);
				}
				return view;
			}
			return null;
		}
		
		/**
		 * 解析需要跳转的内容链接
		 * @param str
		 */
		private CharSequence onParseLinkTxt(MessageEntity entity,JSONArray jsonArray,ViewHolder holder){
			if(jsonArray == null) return  "";
			SpannableStringBuilder builder = new SpannableStringBuilder();
			for (int i = 0; i < jsonArray.length(); i++) {
				try{
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					int type = jsonObject.getInt("type");
					if(type == 1){//文字
						final String content = jsonObject.getString("cont");
						builder.append(content);
					}else if(type == 2){//表情
						//final String content = jsonObject.getString("cont");
						//builder.append(mFaceParse.parseSmileTxt(content));
					}else if(type == 3){//文字跳转
						int typeTmp = 3;//跳转类型
						final String content = jsonObject.optString("cont","  ");
						String customerId = jsonObject.optString("customerId","  ");
						String linkType = jsonObject.optString("linkType",null);
						if("group".equals(linkType)){
							typeTmp = 1;
						}else if("customer".equals(linkType)){
							typeTmp = 2;
						//药品跳转
						}else{
							typeTmp = 3;
						}
						ClickMessageSpan clickSpan = new ClickMessageSpan(DoctorChatActivity.this,typeTmp,customerId,content,entity){
							@Override
							public void updateDrawState(TextPaint ds) {
								super.updateDrawState(ds);
								  ds.setColor(Color.argb(255, 19, 109, 215));       //设置文件颜色
					                ds.setUnderlineText(false);      //设置下划线
							}
						};
//						UnderlineSpan underlineSpan = new UnderlineSpan();
						SpannableString spannableStr = new SpannableString(content);
						final int length = spannableStr.length();
//						spannableStr.setSpan(underlineSpan,0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
						spannableStr.setSpan(clickSpan,0,length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//						spannableStr.setSpan(new ForegroundColorSpan(color.duomei), 0, length,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
						builder.append(spannableStr);
					}else if(type==4){
						final String content = jsonObject.optString("cont","  ");
						ClickMessageSpan clickSpan = new ClickMessageSpan(DoctorChatActivity.this,4,jsonObject.getString("id"),content,entity){
							@Override
							public void updateDrawState(TextPaint ds) {
								super.updateDrawState(ds);
								ds.setColor(Color.argb(255, 19, 109, 215));       //设置文件颜色
					                ds.setUnderlineText(false);      //设置下划线
							}
						};
//						UnderlineSpan underlineSpan = new UnderlineSpan();
						SpannableString spannableStr = new SpannableString(content);
						final int length = spannableStr.length();
//						spannableStr.setSpan(underlineSpan,0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
						spannableStr.setSpan(clickSpan,0,length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//						spannableStr.setSpan(new ForegroundColorSpan(color.duomei), 0, length,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
						builder.append(spannableStr);
					}
				}catch(JSONException e){
					e.printStackTrace();
				}
			}
			return builder;
		}
	}
	
	class ClickMessageSpan extends ClickableSpan {
		// 类型1群2用户 3药品跳转
		int type;
		String id;
		String name;
		WeakReference<Activity> mReference;
		Activity mActivity;
		MessageEntity entity;
		public ClickMessageSpan(Activity activity,int type, String id,
				String name,MessageEntity entity) {
			this.type = type;
			this.id = id;
			this.name = name.trim();
			mReference = new WeakReference<Activity>(activity);
			this.entity=entity;
		}
		@Override
		public void onClick(View widget) {
			Activity activity = mReference.get();
			if(activity == null)return;
			Intent intent;
			switch (type) {
			case 1:{// 群跳转
				intent = new Intent(activity,SalonInformationActivity.class);
				intent.putExtra("id",id);
				activity.startActivity(intent);
				}
				break;
			case 2:// 用户资料跳转
				String loginUserId = SmartFoxClient.getLoginUserId();
				if(loginUserId.equals(id)){
					intent = new Intent(activity,PersonalInformationActivity.class);
				}else{
					intent = new Intent(activity,FriendInformUI.class);
					intent.putExtra("id",id);
				}
				activity.startActivity(intent);
				break;
			case 3:// 药品跳转
				intent = new Intent(activity,ServerShopSeachActivity.class);
				intent.putExtra("name",name);
				intent.putExtra("type",-1);
				activity.startActivity(intent);
				break;
			case 4:
				//name 表示id

				try {
					JSONObject json = entity.getContentJsonArray().getJSONObject(1);
					if(json.has("customer_info")&& 2==json.optInt("customer_info",-100) && "2".equals(id)){//修改界面
						intent=new Intent(DoctorChatActivity.this, DoctorChatMyinformation.class);
						intent.putExtra("modify_Content", json.getString("modify_Content"));
						startActivityForResult(intent, 200);
					}else if(json.has("retJBTZGN") && json.optInt("retJBTZGN")==1){//表示跳转话题 找病友 聊话题 页面
						if("11".equals(id)){//看医生
							//retOfficeCode
							intent = new Intent(DoctorChatActivity.this,DoctorMainUI.class);
							intent.putExtra("name",json.optString("retDiseaseName"));
							intent.putExtra("code", json.optString("retOfficeCode"));
							intent.putExtra("isDoctor", 1);
							startActivity(intent);
						}else if("12".equals(id)){//找病友
							intent = new Intent(activity, FriendMainUI.class);
							startActivity(intent);
						}else if("13".equals(id)){//聊话题
							//retDiseaseName
							intent=new Intent(DoctorChatActivity.this,SalonSeachFromName.class);
							intent.putExtra("name", json.getString("retDiseaseName"));
							startActivity(intent);
						}else{
							JSONObject jsonObject = entity.getContentJsonArray().getJSONObject(2);
							if(jsonObject!=null){
								jsonObject.put("smsTEXT", json.optString("retserial")+" "+id);
								sendMessage(jsonObject, name);
							}
						}
					}else{
						JSONObject jsonObject = entity.getContentJsonArray().getJSONObject(2);
						if(jsonObject!=null){
							jsonObject.put("smsTEXT", json.optString("retserial")+" "+id);
							sendMessage(jsonObject, name);
						}
					}
				} catch (Exception e) {
				}
				
				break;
			}
		}
	}
	
}
